#include "corexmlhandler.h"
#include <QDomDocument>
#include <QDomNode>
#include <QDebug>

CoreXMLHandler::CoreXMLHandler(QObject *parent) :
    QObject(parent), QXmlDefaultHandler()
{
}

bool CoreXMLHandler::startDocument()
{
    doc = QDomDocument();
    currentNode = QDomNode();
    rootNode = QDomNode();
    return true;
}

bool CoreXMLHandler::startElement ( const QString & namespaceURI, const QString & localName, const QString & qName, const QXmlAttributes  & atts )
{
    if(qName == "xml") {
        return true;
    }
    if(!rootNode.isNull() && !currentNode.isNull()) {
        QDomElement e = doc.createElement(qName);
        for (int i = 0; i < atts.count(); i++) {
            e.setAttribute(atts.qName(i),atts.value(i));
        }
        currentNode.appendChild(e);
        currentNode = currentNode.childNodes().at(currentNode.childNodes().count()-1);
        qDebug() << doc.toString();
    }
    else {
        rootNode = doc.createElement(qName);
        for (int i = 0; i < atts.count();i++) {
            rootNode.toElement().setAttribute(atts.qName(i),atts.value(i));
        }
        currentNode = rootNode;
        doc.appendChild(rootNode);
    }
    return true;
}

bool CoreXMLHandler::endElement ( const QString & namespaceURI, const QString & localName, const QString & qName  )
{
    qDebug() << doc.toString();
    if(!rootNode.isNull() && !currentNode.isNull())
    {
        if(currentNode.toElement().tagName() == qName) {
            if (currentNode == rootNode) {
                currentNode.clear();
                // do something with rootNode();
                emit readyParse(rootNode.cloneNode(true));
                rootNode.clear();
                return true;
            }
            currentNode = currentNode.parentNode();
            return true;
        }
        else
        {
            qDebug() << "invalid element closing, found :" << qName;
            qDebug() << "but expected: " << currentNode.toElement().tagName();
        }
    }
    emit malformedXML();
    return false;
}

bool CoreXMLHandler::characters ( const QString & ch  )
{
    if(!currentNode.isNull())
    {
        QDomText t = doc.createTextNode(ch);
        currentNode.appendChild(t);
        return true;
    }
    else {
        emit malformedXML();
        return false;
    }
}

bool CoreXMLHandler::endDocument()
{
    return true;
}
